import { Component, OnInit, ViewChild } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'
import { DatePickerModule } from '../../shared/date-picker/date-picker.module'

declare var $: any
@Component({
  selector: 'sa-manufact-schedule',
  templateUrl: './manufact-schedule.component.html',
  styleUrls: ['./manufact-schedule.component.css']
})
export class ManufactScheduleComponent implements OnInit {
  tableData: any = [] // table的表单数据
  totalCounts: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数

  // 权限
  addPermission: boolean = false
  delPermission: boolean = false
  editPermission: boolean = false
  // 权限结束

  activeSelected: string = '' //row高亮
  searchParams: any = {
    // 搜索字段
    planCode: '',
    planMonth: '',
    deviceName: '',
    iotCardType: '',
    modelVersion: '',
    channelNumber: ''
  }
  fileUp: string = ''
  fileToUpload: File = null //上传文件回调参数
  isShowUpload: boolean = false // 是否是导入的弹框
  editcheckForm: any = {
    planMonth: '',
    deviceName: '',
    iotCardType: '',
    modelVersion: '',
    channelNumber: '',
    salePlanNumber: '',
    stockNumber: '',
    productPlanNumber: '',
    errorMsg: ''
  }
  isUpload: any = '' //是否是导入
  numMessage: string = '' // 导入结果
  // 表单验证
  cleaningOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      iotCardType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择物联卡类型'
          }
        }
      },
      modelVersion: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入版本型号'
          }
        }
      },
      channelNumber: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入通道数'
          }
        }
      },
      salePlanNumber: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入销售计划数量'
          }
        }
      },
      stockNumber: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入库存数量'
          }
        }
      },
      productPlanNumber: {
        trigger: 'blur',
        validators: {
          notEmpty: {
            message: '请输入生产计划数量'
          }
        }
      }
    }
  }
  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }
  ngOnInit() {
    this.initBtn()
    this.initPickerDate()
    this.load()
  }
  //初始化权限按钮
  initBtn() {
    const btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_supplyChain:manufactSchedult')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'manufactSchedule:addBtn' && item.parentId) {
        this.addPermission = true
      }
      if (item.sourceKey === 'manufactSchedule:delBtn' && item.parentId) {
        this.delPermission = true
      }
      if (item.sourceKey === 'manufactSchedule:editBtn' && item.parentId) {
        this.editPermission = true
      }
    }
  }
  //   选择月份函数
  initPickerDate() {
    const that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#scheduleTimePicker')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm',
              language: 'zh-CN',
              weekStart: 1,
              autoclose: 1,
              startView: 'year',
              maxView: 'decade',
              minView: 'year',
              forceParse: false,
              pickerPosition: 'bottom-left'
            })
            .on('changeDate', function (e) {
              const date = e.date
              const year = date.getFullYear()
              const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
              that.searchParams.planMonth = `${year}年${month}月`
            })
          resolve(true)
        })
      })
    })
  }
  delKey(field) {
    if (field) {
      this.searchParams[field] = ''
    }
  }
  // 列表查询
  load() {
    let param = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: this.searchParams
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('productPlan/productPlanPageList.html', reqdata).subscribe(result => {
      let data = []
      if (result.data.isSuccess && result.data.exhibitDatas) {
        data = result.exhibitDatas
        this.tableData = result.data.exhibitDatas
        this.totalCounts = result.data.recordCount
      }
    })
  }
  // 分页回调
  paginate(e) {
    this.activeSelected = ''
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  // 刷新表
  refresh() {
    this.load()
  }

  // 表单查询
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  // 数据导出
  exportData() {
    const params = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      isExport: '1',
      parameters: {
        ...this.searchParams
      }
    }
    common.exprotDataFile(params, 'gridPager', config.BaseURL + 'productPlan/productPlanPageList.html')
  }
  checkCurPage: number = 1
  checkPageSize: number = 10
  checkTotalCounts: number = 0 //分页总条数
  submitCheckTableData: any = [] //核对列表
  successState: string = '' //提交前状态
  projectVersion: string = ''

  // 显示导入弹框
  showImportModal(modal) {
    // 清空选择的文件
    modal.show()
    this.fileToUpload = null
  }

  // 关闭导入弹窗
  cancelUp(modal) {
    modal.hide()
    this.fileToUpload = null
  }

  // 下载模板
  load_module() {
    var elemIF = document.createElement('iframe')
    elemIF.src = config.BaseURL + '/resources/template/productPlan.xlsx'
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  }

  // 清空input type=file输入框的值
  clearFile() {
    this.fileUp = ''
  }

  //文件上传change回调，存储文件信息
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0)
    const isEXCEL =
      this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.fileToUpload.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.fileToUpload = null
      return
    }
  }
  //导入submit
  submitData(modal1, modal2, type) {
    let postParam = new FormData()
    postParam.append('file', this.fileToUpload)
    if (!this.fileToUpload) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    this.jsonApiService.form_http('productPlanTemp/importproductPlanTempData.html', postParam).subscribe(data => {
      if (data.success) {
        modal1.hide()
        this.fileToUpload = null
        this.isShowUpload = true
        this.showSubmitCheck(modal2, data.data)
        this.isUpload = type == '2'
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  //显示
  showSubmitCheck(modal, version) {
    this.projectVersion = version
    this.checkPageSize = 10
    this.checkCurPage = 1
    this.check_table_search(modal)
  }

  // 分页回调
  checkPaginate(e) {
    this.checkCurPage = e.page + 1
    this.checkPageSize = e.rows
    setTimeout(() => {
      this.check_table_search('')
    }, 200)
  }
  queryCheckTable() {
    this.checkPageSize = 10
    this.checkCurPage = 1
    this.check_table_search('')
  }
  // 刷新表
  checkRefresh() {
    this.check_table_search('')
  }

  //关闭
  cancelSubmitCheck(modal2) {
    this.successState = ''
    this.submitCheckTableData = []
    this.projectVersion = ''
    modal2.hide()
  }
  //批量删除
  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowId: string = '' //批量
  //查询
  check_table_search(modal) {
    let param = {
      pageSize: this.checkPageSize,
      nowPage: this.checkCurPage,
      parameters: {
        version: this.projectVersion,
        successState: this.successState
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('productPlanTemp/productPlanTempPageList.html', reqdata).subscribe(result => {
      if (result.success) {
        this.submitCheckTableData = result.data.exhibitDatas
        if (modal) modal.show()
        for (let item of this.submitCheckTableData) {
          item['isChecked'] = false
        }
        this.allChecked = false
        this.selected = []
        this.rowId = ''
        this.checkTotalCounts = result.data.recordCount
        this.numMessage = result.message
      } else {
        this.numMessage = ''
      }
    })
  }
  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.submitCheckTableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowId = ''
    } else {
      var temArr = []
      for (let item of this.submitCheckTableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.rowId)
      }
      this.rowId = temArr.join(',')
    }
  }
  //提交
  submitCheck(modal) {
    let isSubmit = true
    if (this.submitCheckTableData.length == 0) {
      this.jsonApiService.message('暂无需要提交核对的数据')
      return
    }

    if (isSubmit) {
      this.jsonApiService
        .http_obj('productPlanTemp/submitproductPlanTempData.html', { version: this.projectVersion })
        .subscribe(result => {
          this.jsonApiService.message(result.message)
          if (result.success) {
            this.successState = ''
            this.submitCheckTableData = []
            this.projectVersion = ''
            // this.resetForm()
            modal.hide()
            this.load()
          }
        })
    }
  }
  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowId = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.submitCheckTableData.length ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }
  // 弹框批量删除
  batchDelete() {
    if (this.selected.length && this.rowId != '') {
      this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
        let reqdata = 'ids=' + this.rowId
        this.jsonApiService.http('productPlanTemp/removeProductPlanTempByIds.html', reqdata).subscribe(data => {
          this.jsonApiService.message(data.message)
          this.check_table_search('')
        })
      })
    } else {
      this.jsonApiService.message('请选中最少一条数据')
    }
  }
  //编辑
  editSubmitCheck(row, modal) {
    this.editcheckForm = { ...row }
    $('#dataCleaning').data('bootstrapValidator').resetForm()
    modal.show()
    this.initCreateDate()
  }
  //关闭编辑
  closeEditSubmitCheck(modal) {
    modal.hide()
  }
  //初始化日期
  initCreateDate() {
    const that = this
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#editPlanMonth')
          .datetimepicker({
            format: 'yyyy-mm',
            language: 'zh-CN',
            weekStart: 1,
            autoclose: 1,
            startView: 'year',
            maxView: 'decade',
            minView: 'year',
            forceParse: false,
            pickerPosition: 'bottom-left'
          })
          .on('changeDate', function (e) {
            const date = e.date
            const year = date.getFullYear()
            const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
            that.editcheckForm.planMonth = `${year}年${month}月`
            // that.countPay()
          })
      })
    })
  }
  //删除
  delSubmitCheck(row) {
    this.jsonApiService.confirm_message('此操作将删除临时数据,确认要删除').then(() => {
      let reqdata = 'ids=' + row.id
      this.jsonApiService.http('productPlanTemp/removeProductPlanTempByIds.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.check_table_search('')
        }
      })
    })
  }
  edit_domCode(row, modal) {
    $('#dataCleaning').data('bootstrapValidator').resetForm()
    this.isUpload = false
    this.editcheckForm = { ...row }
    modal.show()
  }
  del_domCode(row) {
    this.jsonApiService.confirm_message('此操作将删除数据,确认要删除').then(() => {
      this.jsonApiService.http_get(`productPlan/deleteProductPlan.html?ids=${row.id}`).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  submitEditSubmitCheck(modal) {
    $('#dataCleaning').bootstrapValidator('validate') //开启验证
    let isValid = $('#dataCleaning').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.jsonApiService.json_http('productPlan/updateProductPlan.html', this.editcheckForm).subscribe(result => {
        this.jsonApiService.message(result.message)
        if (result.success) {
          modal.hide()
          this.load()
        }
      })
    }
  }
  validateChange(key) {
    this.editcheckForm[key] = this.editcheckForm[key].replace(/^(0+)|[^\d]+/g, '')
  }
}
